<?php

namespace app\controllers;
use yii\data\ActiveDataProvider;
use Yii;
use app\models\User;
use yii\filters\auth\QueryParamAuth;


class AppUserController extends \yii\rest\ActiveController
{
    public $modelClass = 'app\models\User';
    
    public function behaviors()
    {
        return \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            //响应返回json
            'contentNegotiator' => [
                'formats' => [
                    'application/json' => \yii\web\Response::FORMAT_JSON,
                ],
            ],
            //接口采用参数带token的方式进行认证 
            'authenticator' => [
            'class' => QueryParamAuth::classname(),
            'except' => ['register','login'],
           
    ]
            ]);
    }
    /**
     *用户注册
     */
    public function actionRegister()
     {
         $model = new $this->modelClass;
         $model->scenario = 'register';

         // 用用户输入来填充模型的特性
       if(!isset($_POST["username"])||!isset($_POST["email"])||!isset($_POST["password"])||!isset($_POST["tel"]) )
           {
            throw new \yii\web\HttpException(400, '请提交正确的表单！'); 
            }
         else 
           {

            
        try {
            $tel =User::findOne([
     'tel' => $_POST["tel"]
         ]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }
       if($tel!=null)
        throw new \yii\web\HttpException(422, '对不起，该号码已存在！');            


            $hash = Yii::$app->getSecurity()->generatePasswordHash($_POST["password"]);
            $model->email=$_POST["email"];
            $model->tel=$_POST["tel"];
            $model->username=$_POST["username"];
            $model->password_hash=$hash;
            $model->save();
             return $model; 
            }
            
         
        
     }
     
     /*
      * 用户登录
      */
     public function actionLogin()
     {

       if (!isset($_POST["tel"])||!isset($_POST["password"]))
         { throw new \yii\web\HttpException(400, '请填写正确的参数！');}

        try {
            $user=User::findOne(
    ['tel' => $_POST["tel"]]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }

        if($user===null)
    	{ throw new \yii\web\HttpException(400, '用户不存在！');}
        else
       {
          $hash=$user->password_hash;
        }
       
        
        if (Yii::$app->getSecurity()->validatePassword($_POST["password"], $hash)) 
        {
            //生成伪随机数作为令牌
            $access_token = Yii::$app->getSecurity()->generateRandomString();
            $user->scenario = 'register';//由于没有设定login场景，用register代替
            $user->access_token=$access_token;
            $user->save();
            return $user;
        } else 
            {
             throw new \yii\web\HttpException(400, '用户名或密码错误！');
            }
         
     }
     
     /*
      *  用户删除接口
      */
 	 public function actionDel()
     {

     	  if (!isset($_POST["id"])||!isset($_POST["password"]))
         { throw new \yii\web\HttpException(400, '请填写正确的参数！');} 
             $user=User::findOne(
             ['id' => $_POST["id"]]);
             if($user===null)
            { throw new \yii\web\HttpException(400, '用户不存在！');}
            else
            {
                $hash=$user->password_hash;
            }
             if (Yii::$app->getSecurity()->validatePassword($_POST["password"], $hash))
             {
                $user->delete();              
             }
              else {
                    throw new \yii\web\HttpException(400, '对不起，你没有权限删除该用户！');
                    }
     }
     
     /*
      *  修改密码接口
      */
 	 public function actionXgmm()
     {

     	  if (!isset($_POST["id"])||!isset($_POST["oldpassword"])||!isset($_POST["newpassword"]))
         { throw new \yii\web\HttpException(400, '请填写正确的参数！');} 
             $user=User::findOne(
             ['id' => $_POST["id"]]);
             if($user===null)
            { throw new \yii\web\HttpException(400, '用户不存在！');}
            else
            {
                $user->scenario = 'register';
                $hash=$user->password_hash;
            }
             if (Yii::$app->getSecurity()->validatePassword($_POST["oldpassword"], $hash))
             {
                 $hash = Yii::$app->getSecurity()->generatePasswordHash($_POST["newpassword"]);
                 $user->password_hash=$hash;
                 $user->save();
                 return $user;
             }
              else {
                    throw new \yii\web\HttpException(400, '对不起，你没有权限修改密码！');
                    }
     }        
     
    
}
